//
//  WBEmotionPageView.m
//  新浪微博项目
//
//  Created by neng on 15/12/22.
//  Copyright (c) 2015年 neng. All rights reserved.
//

#define EmotionRows 3
#define EmotionCols 7
#define Padding 20

#import "WBEmotionPageView.h"
#import "WBEmotion.h"
#import "WBEmotionButton.h"
#import "WBEmotionPopView.h"

@interface WBEmotionPageView ()

@property (nonatomic,weak) WBEmotionPopView *popView;

@end

@implementation WBEmotionPageView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        //添加长按手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressView:)];
        [self addGestureRecognizer:longPress];
    }
    return self;
}

- (WBEmotionPopView *)popView
{
    if (!_popView) {
        _popView = [WBEmotionPopView popView];
    }
    return _popView;
}

//长按view
- (void)longPressView:(UILongPressGestureRecognizer *)gesture
{
    //获得长按的点
    CGPoint point = [gesture locationInView:self];
    WBEmotionButton *btn = [self emotionButtonWithPoint:point];
    
    switch (gesture.state) {
        case UIGestureRecognizerStateCancelled :
        case UIGestureRecognizerStateEnded:
            
            if (btn) {  //如果在某个btn上，就插入这个表情
                
                [self insertEmotion:btn.emotion];
            }
            
            break;
            
        case UIGestureRecognizerStateBegan :
        case UIGestureRecognizerStateChanged:
            //显示
            [self.popView showFromView:btn];
            
            break;
        default:
            break;
    }
}

//获得手势所在的按钮
- (WBEmotionButton *)emotionButtonWithPoint:(CGPoint)point
{
    //遍历子控件
    for (int i = 0; i < self.subviews.count - 1; i ++) {
        
        WBEmotionButton *btn = self.subviews[i];
        if (CGRectContainsPoint(btn.frame, point)) {
            
            return btn;
        }
    }
    return nil;
}

- (void)setEmotions:(NSArray *)emotions
{
    _emotions = emotions;
    
    for (int i = 0; i < emotions.count; i++) {
        
        //创建按钮
        WBEmotionButton *btn = [WBEmotionButton buttonWithType:UIButtonTypeCustom];
        
        //监听事件
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        //取出对应表情
        WBEmotion *emotion = emotions[i];
        btn.emotion = emotion;
        
        [self addSubview:btn];
    }
    
    //最后的退格表情
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"compose_emotion_delete"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"compose_emotion_delete_highlighted"] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(backward) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:btn];
    
}

//点击表情
- (void)btnClick:(WBEmotionButton *)btn
{
    
    //将popView显示在按钮上
    [self.popView showFromView:btn];
    
    [self insertEmotion:btn.emotion];
    
    //要重新布局，不然看不到新的表情
    [self setNeedsLayout];
}

//通过通知的方式插入表情并移除popView
- (void)insertEmotion:(WBEmotion *)emotion
{
    //通过通知的方式把选中的表情传到textView
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    userInfo[WBEmotionKey] = emotion;
    [[NSNotificationCenter defaultCenter] postNotificationName:WBEmotionKeyboardDidClickedEmotionKey object:nil userInfo:userInfo];

    //延迟消失
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.popView removeFromSuperview];
    });
}

//点击退格
- (void)backward
{
    //因为和textView隔着太多层，用代理不方便，所以使用通知
    [[NSNotificationCenter defaultCenter] postNotificationName:WBEmotionKeyboardDidClikedBackwardKey object:nil];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    //排布表情
    CGFloat emotionW = (self.width - (2 * Padding)) / EmotionCols;
    CGFloat emotionH = (self.height - Padding) / EmotionRows;
    CGFloat emotionX = 0;
    CGFloat emotionY = 0;
    CGFloat row = 0;
    CGFloat col = 0;
    
    for (int i = 0; i < self.subviews.count - 1; i++) {
        
        row = i / EmotionCols;
        col = i % EmotionCols;
        
        emotionX = Padding + col * emotionW;
        emotionY = Padding + row * emotionH;
        
        UIButton *emotion = self.subviews[i];
        emotion.frame = CGRectMake(emotionX, emotionY, emotionW, emotionH);
    }
    
    //取出退格按钮
    UIButton *btn = self.subviews[self.subviews.count - 1];
    CGFloat btnX = self.width - btn.width - Padding;
    CGFloat btnY = self.height - btn.height ;
    btn.frame = CGRectMake(btnX, btnY, emotionW, emotionH);
}

@end
